package com.kk.interceptor;

import com.alibaba.fastjson.JSON;
import com.kk.util.redis.RedisUtils;
import com.kk.util.result.Result;
import lombok.extern.log4j.Log4j2;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author: kevin
 * @data: 2018-08-30 15:29
 * @desc:
 */
@Log4j2
public class TokenInterceptor implements HandlerInterceptor {

    //注；spring中只有Bean才会自动注入，new TokenInterceptor()不会自动注入其中的类，所以在WebMvcConfiguration此处@Bean实现RedisUtils的注入
    @Autowired
    RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            log.info(method);
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String origin = request.getHeader(HttpHeaders.ORIGIN);
        String token = request.getHeader("token");

        if (StringHelper.isNotEmpty(token)) {
            try {
                boolean isExist = false;
                if (redisUtils != null) {
                    isExist = redisUtils.exists(token);
                } else {
                    log.error("redisUtils为null");
                    return false;
                }
                if (isExist) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                log.error("token无效", origin, e.getMessage());
                return false;
            }
        } else {
            log.error("请求头header中token为空", origin);
            return false;
        }
//        }
    }

    private void errorHandler(HttpServletResponse response, String origin, String token) throws IOException {
        PrintWriter pw = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(response.getOutputStream(),
                    "UTF-8");
            pw = new PrintWriter(osw, true);
            String jsonStr = JSON.toJSONString(Result.error("403", "token无效"));
            pw.write(jsonStr);
            pw.flush();
            pw.close();
            osw.close();
        } catch (UnsupportedEncodingException e) {
            log.error("过滤器返回信息失败:" + e.getMessage(), e);
        } catch (IOException e) {
            log.error("过滤器返回信息失败:" + e.getMessage(), e);
        } finally {
            if (null != pw) {
                pw.close();
            }
            if (null != osw) {
                osw.close();
            }
        }
    }

}
